<template>
  <el-form :label-position="config.labelPosition || 'right'" class="FormConfigBox" ref="form" :model="value" :rules="_config.rules" :label-width="_config.labelWidth" :size="defaultFormItemSize" @submit.native.prevent>
    <el-row style="height: 100%" :type="config.justify ? 'flex':''" :justify="config.justify" :gutter="config.gutter || 20" :class="{ 'flex-warp': flexWarp }">
      <template v-for="(option, index) in options">
        <el-col :key="index" :span="config.span || option.span || 24">
          <el-form-item  :label="`${option.label}：`" :prop="option.prop"   :clearable="option.clearable || _config.clearable">
            <ConfigItem :objectRef.sync="objectRefs[option.prop]" customClass="configForm-item" :option="option" v-model="value[option.prop]" :disabled="disabled" :readonly="readonly || option.readonly" :size="defaultFormItemSize">
              <slot v-if="option.slot" :name="option.prop" />
            </ConfigItem>
          </el-form-item>
        </el-col>
      </template>
    </el-row>
  </el-form>
</template>
<script>
import ConfigItem from '../ConfigItem/index';
import _ from 'lodash'

export default {
  components: {
    ConfigItem
  },
  props: {
    config: {
      // 绑定值
      type: Object,
      default: () => ({})
    },
    options: {
      // 表单项
      type: Array,
      default: () => []
    },
    value: {
      // 绑定值
      type: Object,
      default: () => ({})
    },
    onSubmit: {
      // 绑定值
      type: Function,
      default: () => { }
    },
    flexWarp: Boolean,
    readonly: Boolean,
    disabled: Boolean
  },
  model: {
    prop: 'value',
    event: 'on-model-change'
  },
  name: 'FormConfigBox',
  data () {
    return {
      objectRefs: {},
      defaultConfig: {
        labelWidth: '120px',
        clearable: true,
        rules: {}
      }
    };
  },
  created () {
    this.defaultValues = _.cloneDeep(this.value)
  },
  mounted () { },
  methods: {
    handleSubmit (callback = () => { }) {
      this.$refs.form.validate((valid) => {
        if (valid) {
          callback(this.value)
          this.onSubmit(this.value);
        }
      })
    },
    handleReset () {
      this.$refs.form.resetFields();
      const newObj = _.cloneDeep(this.defaultValues)
      this.$emit('on-model-change', newObj)
    }
  },
  computed: {
    _config () {
      return {
        ...this.defaultConfig,
        ...this.config
      }
    }
  },
  watch: {}
}
</script>
<style lang="scss" scoped>
.FormConfigBox {
  .config-item {
    width: 100%;
  }
}
</style>
